﻿using System;
using Framework.Exceptions;
using Framework.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace SQLRepositories
{
    public class EntityBaseRepository<T> : BaseRepository
    {
        public EntityBaseRepository(IDBEconomicInformationServiceContext context) 
            : base(context)
        {}

        public virtual void Update(T item)
        {
            try
            {
                Context.SaveChanges();
                Logger.Write(string.Format("Item {0} successfully updated", typeof(T).Name),
                            LogCategory.DAS, (int)EventPriority.Normal);
            }
            catch (Exception e)
            {
                ExceptionHandlingManager.HandleException(e, PolicyNames.DASPolicy);
            }

        }

        protected virtual void Insert(Action insertAction)
        {
            try
            {
                insertAction();
            }
            catch (Exception exception)
            {
                ExceptionHandlingManager.HandleException(exception, PolicyNames.DASPolicy);
            }
        }

        protected virtual TResult Insert<TResult>(Func<TResult> insertFunction)
        {
            var result = default(TResult);

            try
            {
                result = insertFunction();
            }
            catch (Exception exception)
            {
                ExceptionHandlingManager.HandleException(exception, PolicyNames.DASPolicy);
            }

            return result;
        }

        protected virtual TResult Get<TResult>(Func<TResult> getFunction)
        {
            var result = default(TResult);

            try
            {
                result = getFunction();
            }
            catch (Exception exception)
            {
                ExceptionHandlingManager.HandleException(exception, PolicyNames.DASPolicy);
            }

            return result;
        }

        protected virtual void Delete(Action deleteAction)
        {
            try
            {
                deleteAction();
            }
            catch (Exception exception)
            {
                ExceptionHandlingManager.HandleException(exception, PolicyNames.DASPolicy);
            }
        }
    }
}
